const db = require("./db");

function Cart(cart) {
    this.id = cart.id;
    this.userId = cart.userId;
    this.productId = cart.productId;
    this.num = cart.num;
    this.size = cart.size;
    this.isDelete = cart.isDelete;
}
Cart.addCart = (cart, callback) => {
    let selectSql = "INSERT INTO cart (id, userId, productId, num, size, isDelete) values(null, ?, ?, ?, ?, 1) ";
    db.query(selectSql, [cart.userId, cart.productId, cart.num, cart.size], (err, result) => {
        if (err) return callback(err);
        callback(err, result);
    });
}
Cart.deleteCart = (id, callback) => {
    let idStr = "";
    for (let i = 0; i < id.length; i++) {
        if (i == 0) {
            idStr = idStr + id[i];
        } else {
            idStr = idStr + "," + id[i];
        }
    }
    let delSql = `UPDATE cart SET isDelete =0 WHERE id in (${idStr})`;
    console.log(delSql);
    db.query(delSql, (err, res) => {
        if (err) return callback(err);
        callback(err, res);
    })
}
Cart.updateCart = (cart, callback) => {
    let selectSql = 'UPDATE cart SET num = ?, size = ? WHERE id = ?';
    db.query(selectSql, [cart.num, cart.size, cart.id], (err, res) => {
        if (err) return callback(err);
        callback(err, res);
    })
}
Cart.queryCart = (id, callback) => {
    let selectSql = 'SELECT c.id, c.productId, c.num, c.size, p.proName, p.price, p.oldPrice, p.num as productNum, p.statu, p.size as productSize from cart as c left join product as p on c.productId = p.id where c.userId = ? and c.isDelete = 1';
    db.query(selectSql, [id], (err, result) => {
        if (err) return callback(err);
        callback(err, result);
    })
}
Cart.queryCartPaging = (id, page, callback) => {
    let selectSql = 'SELECT c.id, c.productId, c.num, c.size, p.proName, p.price, p.oldPrice, p.num as productNum, p.statu, p.size as productSize from cart as c left join product as p on c.productId = p.id where c.userId =? ';

    selectSql += " LIMIT ?,?";
    db.query(selectSql, [id, (page.page - 1) * page.size, page.size], (err, res) => {
        if (err) return callback(err);
        callback(err, res);
    });
}
Cart.countCart = (id, callback) => {
    let selectSql = "select count(c.id) from cart as c left join product as p on c.productId = p.id where c.userId = ?";
    db.query(selectSql,[id], (err, result) => {
        if (err) return callback(err);
        callback(err, result[0]);
    })
}

module.exports = Cart;